from flask import Blueprint, request, jsonify, current_app
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename
import os
import uuid
import logging

logger = logging.getLogger('Personal_Blog_System')

# 创建上传API蓝图
upload_api = Blueprint('upload_api', __name__, url_prefix='/api/upload')

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'mp4', 'mp3', 'zip', 'rar'}

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@upload_api.route('/image', methods=['POST'])
@login_required
def upload_image():
    """上传图片"""
    try:
        if 'file' not in request.files:
            return jsonify({'success': False, 'message': '没有选择文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'success': False, 'message': '没有选择文件'}), 400
        
        if not allowed_file(file.filename):
            return jsonify({'success': False, 'message': '不支持的文件类型'}), 400
        
        # 生成安全的文件名
        filename = secure_filename(file.filename)
        name, ext = os.path.splitext(filename)
        unique_filename = f"{name}_{uuid.uuid4().hex[:8]}{ext}"
        
        # 创建上传目录
        upload_folder = os.path.join(current_app.root_path, 'files', 'images')
        os.makedirs(upload_folder, exist_ok=True)
        
        # 保存文件
        file_path = os.path.join(upload_folder, unique_filename)
        file.save(file_path)
        
        # 生成访问URL
        file_url = f"/files/images/{unique_filename}"
        
        return jsonify({
            'success': True,
            'message': '图片上传成功',
            'data': {
                'filename': unique_filename,
                'original_name': file.filename,
                'url': file_url,
                'size': os.path.getsize(file_path),
                'type': 'image'
            }
        })
        
    except Exception as e:
        logger.error(f"上传图片失败: {str(e)}")
        return jsonify({'success': False, 'message': '上传图片失败'}), 500


@upload_api.route('/avatar', methods=['POST'])
@login_required
def upload_avatar():
    """上传头像"""
    try:
        if 'avatar' not in request.files:
            return jsonify({'success': False, 'message': '没有选择文件'}), 400
        
        file = request.files['avatar']
        if file.filename == '':
            return jsonify({'success': False, 'message': '没有选择文件'}), 400
        
        # 只允许图片文件
        if not file.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
            return jsonify({'success': False, 'message': '只支持图片文件'}), 400
        
        # 检查文件大小 (2MB)
        if file.content_length and file.content_length > 2 * 1024 * 1024:
            return jsonify({'success': False, 'message': '文件大小不能超过2MB'}), 400
        
        # 生成安全的文件名
        filename = secure_filename(file.filename)
        name, ext = os.path.splitext(filename)
        unique_filename = f"{uuid.uuid4().hex}{ext}"
        
        # 创建头像上传目录
        upload_folder = os.path.join(current_app.root_path, 'files', 'avatars')
        os.makedirs(upload_folder, exist_ok=True)
        
        # 保存文件
        file_path = os.path.join(upload_folder, unique_filename)
        file.save(file_path)
        
        # 生成访问URL
        file_url = f"/files/avatars/{unique_filename}"
        
        # 更新用户头像
        from models import User
        from extensions import db
        current_user.avatar = file_url
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '头像上传成功',
            'data': {
                'filename': unique_filename,
                'avatar_url': file_url,
                'size': os.path.getsize(file_path)
            }
        })
        
    except Exception as e:
        logger.error(f"上传头像失败: {str(e)}")
        return jsonify({'success': False, 'message': '上传头像失败'}), 500


